<template>
  <div class="history">
    <!-- 页面主体 -->
    <v-main>
      <div class="history-wrapper">
        <!-- 店铺数据总览 -->
        <div class="store-summary">
          <div class="summary-title clearfix">
            <div class="name">
              <span>历史数据</span>
              <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                <i class="iconfont" style="font-weight: normal;">&#xe72d;</i>
                <div slot="content">
                  近7日平均新增顾客：最近7日（不含今日）每日新增顾客的平均值
                  <br>
                  <br>
                  近7日平均店内人数：最近7日（不含今日）每日店内人数的平均值
                  <br>
                  <br>
                  近7日平均进店人次：最近7日（不含今日）每日进店人次的平均值
                  <br>
                  <br>
                  近7日平均进店转化率：最近7日（不含今日）每日进店转化率的平均值
                  <br>
                  <br>
                  近30日总新增顾客：最近30日（不含今日）新增顾客的总数
                  <br>
                  <br>
                  近30日最热区域：最近30日（不含今日）人数累计最多的区域
                  <br>
                  <br>
                  近30日总店内人数：最近30日（不含今日）店内人数的总数（去重）
                  <br>
                  <br>
                  近30日总进店人次：最近30日（不含今日）进店人次的总数
                  <br>
                </div>
              </el-tooltip>
            </div>
          </div>
          <div class="summary-main clearfix">
            <div class="summary-wrapper">
              <div class="summary-item">
                <div class="data-compare clearfix">
                  <div class="compare-item">
                    <div class="label">近7日平均新增顾客</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                  :endVal="dataComparation && dataComparation.seven_new_avg !== null ? Number(dataComparation.seven_new_avg) : 0"
                                  :decimals="0"
                                  :duration="2"
                                  :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.seven_new_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.seven_new_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.seven_new_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.seven_new_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.seven_new_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.seven_new_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                  <div class="compare-item">
                    <div class="label">近7日平均店内人数</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                  :endVal="dataComparation && dataComparation.seven_num_avg !== null ? Number(dataComparation.seven_num_avg) : 0"
                                  :decimals="0"
                                  :duration="2"
                                  :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.seven_num_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.seven_num_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.seven_num_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.seven_num_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.seven_num_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.seven_num_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>

                  </div>
                  <div class="compare-item">
                    <div class="label">近7日平均进店人次</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                  :endVal="dataComparation && dataComparation.seven_times_avg !== null ? Number(dataComparation.seven_times_avg) : 0"
                                  :decimals="0"
                                  :duration="2"
                                  :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.seven_times_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.seven_times_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.seven_times_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.seven_times_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.seven_times_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.seven_times_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                  <div class="compare-item">
                    <div class="label">近7日平均进店转化率</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                  :endVal="dataComparation && dataComparation.seven_convert_avg !== null ? Number(dataComparation.seven_convert_avg.slice(0,-1)) : 0"
                                  :decimals="2"
                                  :duration="2"
                                  :options="cuConfig">
                      </i-count-up>
                      <span class="unit">%</span>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.seven_convert_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.seven_convert_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.seven_convert_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.seven_convert_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.seven_convert_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.seven_convert_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="summary-wrapper">
              <div class="summary-item">
                <div class="data-compare clearfix">
                  <div class="compare-item">
                    <div class="label">近30日总新增顾客</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                :endVal="dataComparation && dataComparation.thirty_new_sum !== null ? Number(dataComparation.thirty_new_sum): 0"
                                :decimals="0"
                                :duration="2"
                                :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.thirty_new_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.thirty_new_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.thirty_new_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.thirty_new_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.thirty_new_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.thirty_new_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                  <div class="compare-item">
                    <div class="label">近30日最热区域</div>
                    <div class="value" :style="{ 'font-size': dataComparation && dataComparation['hottest-zone'] !== null ? dataComparation['hottest-zone'].length >= 7 ? '26px' : '' : '' }">{{dataComparation && dataComparation['hottest-zone'] !== null ? dataComparation['hottest-zone'] : '暂无'}}</div>
                  </div>
                  <div class="compare-item">
                    <div class="label">近30日总店内人数</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                :endVal="dataComparation && dataComparation.thirty_num_sum !== null ? Number(dataComparation.thirty_num_sum) : 0"
                                :decimals="0"
                                :duration="2"
                                :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.thirty_num_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.thirty_num_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.thirty_num_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.thirty_num_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.thirty_num_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.thirty_num_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                  <div class="compare-item">
                    <div class="label">近30日总进店人次</div>
                    <div class="value">
                      <i-count-up :startVal="0"
                                :endVal="dataComparation && dataComparation.thirty_times_sum !== null ? Number(dataComparation.thirty_times_sum) : 0"
                                :decimals="0"
                                :duration="2"
                                :options="cuConfig">
                      </i-count-up>
                    </div>
                    <div :class="[ 'desc', dataComparation && dataComparation.thirty_times_ratio.includes('+') ? 'rise' : dataComparation && dataComparation.thirty_times_ratio.includes('-') ? 'fall' : '' ]"
                          v-if="dataComparation && dataComparation.thirty_times_ratio !== null ">
                      <span>{{`环比上期 ${dataComparation.thirty_times_ratio}`}}</span>
                      <i class="iconfont" v-show="dataComparation.thirty_times_ratio.includes('+')">&#xe6ca;</i>
                      <i class="iconfont" v-show="dataComparation.thirty_times_ratio.includes('-')">&#xe6cb;</i>
                    </div>
                    <div class="mom" v-else>
                      暂无数据，无法环比
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="history-tabs">
        <el-row class="summary-main clearfix">
          <el-col :span="8" style="margin-right:20px;">
            <el-date-picker v-show="!isOnlyOneDay"
                            :clearable="false"
                            v-model="choosenDate"
                            type="daterange"
                            size="small"
                            value-format="yyyy-MM-dd"
                            :picker-options="pickerOptions"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
            </el-date-picker>
          </el-col>
          <el-col :span="8" style="margin-right:20px;">
            <el-date-picker style="width:350px;"
                            :clearable="false"
                            v-model="oneDayChoose"
                            v-show="isOnlyOneDay"
                            type="date"
                            size="small"
                            value-format="yyyy-MM-dd"
                            :picker-options="pickerOptions"
                            placeholder="选择日期">
                            <!-- :picker-options="pickerOptions1"> -->
            </el-date-picker>
          </el-col>
          <el-col :span="8" class="timeOptions">
            <span :class="[{ active: activeDateOption === 'first' }, 'option']" @click="handleDate(0)">今天</span>
            <span :class="[{ active: activeDateOption === 'second' }, 'option']" @click="handleDate(1)">昨天</span>
            <span v-show="!isOnlyOneDay" :class="[{ active: activeDateOption === 'third' }, 'option']" @click="handleDate(2)">7天</span>
            <span v-show="!isOnlyOneDay" :class="[{ active: activeDateOption === 'fourth' }, 'option']" @click="handleDate(3)">14天</span>
            <span v-show="!isOnlyOneDay" :class="[{ active: activeDateOption === 'fifth' }, 'option']" @click="handleDate(4)">30天</span>
          </el-col>
        </el-row>
        <el-tabs v-model="activeTabsName" @tab-click="handleSwitchTab">
          <!-- tab - 新增顾客 -->
          <el-tab-pane label="新增顾客" name="newCustomerNumberView">
            <div class="customer-number-view data-view">
              <div class="panel-title">趋势图</div>
              <div class="panel-charts">
                <v-echart :options="newCustomerNumberEchartOption"></v-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                  <i class="iconfont">&#xe72d;</i>
                  <div slot="content">
                    新增顾客：选择日期首次来到店内的顾客数
                    <br>
                    <br>
                    店内人数： 选择日期店内的顾客数（排重）
                    <br>
                    <br>
                    进店人次： 选择日期顾客进入店内的次数
                    <br>
                    <br>
                    经过人数： 店外摄像头捕捉到的人数（排重）
                    <br>
                    <br>
                    进店转化率： 进店转化率=店内人数/经过人数*100%
                  </div>
                </el-tooltip>
                <span class="save-csv-link" @click="saveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          show-summary
                          :summary-method="tableSummaryMethod"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   :label="(this.isSameDay? '时间': '日期')"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="newCustomerNumber"
                                   align="center"
                                   sortable
                                   label="新增顾客">
                    <template slot-scope="scope">{{ scope.row.newCustomerNumber !== null && scope.row.newCustomerNumber !== undefined ? scope.row.newCustomerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerNumber"
                                   align="center"
                                   sortable
                                   label="店内人数">
                    <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerTimes"
                                   align="center"
                                   sortable
                                   label="进店人次">
                    <template slot-scope="scope">{{ scope.row.customerTimes !== null && scope.row.customerTimes !== undefined ? scope.row.customerTimes : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="passengerNumber"
                                   align="center"
                                   sortable
                                   label="经过人数">
                    <template slot-scope="scope">{{ scope.row.passengerNumber !== null && scope.row.passengerNumber !== undefined ? scope.row.passengerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerPercentConv"
                                   align="center"
                                   sortable
                                   :sort-method="sortPercentConvMethods"
                                   label="进店转化率">
                    <template slot-scope="scope">{{ scope.row.customerPercentConv !== null && scope.row.customerPercentConv !== undefined ? scope.row.customerPercentConv : '0.00%' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 店内人数 -->
          <el-tab-pane label="店内人数" name="customerNumberView">
            <div class="customer-number-view data-view">
              <div class="panel-title">趋势图</div>
              <div class="panel-charts">
                <v-echart :options="customerNumberEchartOption"></v-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                  <i class="iconfont">&#xe72d;</i>
                  <div slot="content">
                    新增顾客：选择日期首次来到店内的顾客数
                    <br>
                    <br>
                    店内人数： 选择日期店内的顾客数（排重）
                    <br>
                    <br>
                    进店人次： 选择日期顾客进入店内的次数
                    <br>
                    <br>
                    经过人数： 店外摄像头捕捉到的人数（排重）
                    <br>
                    <br>
                    进店转化率： 进店转化率=店内人数/经过人数*100%
                  </div>
                </el-tooltip>
                <span class="save-csv-link" @click="saveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          show-summary
                          :summary-method="tableSummaryMethod"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   :label="(this.isSameDay? '时间': '日期')"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="newCustomerNumber"
                                   align="center"
                                   sortable
                                   label="新增顾客">
                    <template slot-scope="scope">{{ scope.row.newCustomerNumber !== null && scope.row.newCustomerNumber !== undefined ? scope.row.newCustomerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerNumber"
                                   align="center"
                                   sortable
                                   label="店内人数">
                    <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerTimes"
                                   align="center"
                                   sortable
                                   label="进店人次">
                    <template slot-scope="scope">{{ scope.row.customerTimes !== null && scope.row.customerTimes !== undefined ? scope.row.customerTimes : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="passengerNumber"
                                   align="center"
                                   sortable
                                   label="经过人数">
                    <template slot-scope="scope">{{ scope.row.passengerNumber !== null && scope.row.passengerNumber !== undefined ? scope.row.passengerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerPercentConv"
                                   align="center"
                                   sortable
                                   :sort-method="sortPercentConvMethods"
                                   label="进店转化率">
                    <template slot-scope="scope">{{ scope.row.customerPercentConv !== null && scope.row.customerPercentConv !== undefined ? scope.row.customerPercentConv : '0.00%' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 进店人次 -->
          <el-tab-pane label="进店人次" name="customerTimesView">
            <div class="customer-times-view data-view">
              <div class="panel-title">趋势图</div>
              <div class="panel-charts">
                <v-echart :options="customerTimesEchartOption"></v-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                  <i class="iconfont">&#xe72d;</i>
                  <div slot="content">
                    新增顾客：选择日期首次来到店内的顾客数
                    <br>
                    <br>
                    店内人数： 选择日期店内的顾客数（排重）
                    <br>
                    <br>
                    进店人次： 选择日期顾客进入店内的次数
                    <br>
                    <br>
                    经过人数： 店外摄像头捕捉到的人数（排重）
                    <br>
                    <br>
                    进店转化率： 进店转化率=店内人数/经过人数*100%
                  </div>
                </el-tooltip>
                <span class="save-csv-link" @click="saveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          show-summary
                          :summary-method="tableSummaryMethod"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   :label="(this.isSameDay? '时间': '日期')"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="newCustomerNumber"
                                   align="center"
                                   sortable
                                   label="新增顾客">
                    <template slot-scope="scope">{{ scope.row.newCustomerNumber !== null && scope.row.newCustomerNumber !== undefined ? scope.row.newCustomerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerNumber"
                                   align="center"
                                   sortable
                                   label="店内人数">
                    <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerTimes"
                                   align="center"
                                   sortable
                                   label="进店人次">
                    <template slot-scope="scope">{{ scope.row.customerTimes !== null && scope.row.customerTimes !== undefined ? scope.row.customerTimes : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="passengerNumber"
                                   align="center"
                                   sortable
                                   label="经过人数">
                    <template slot-scope="scope">{{ scope.row.passengerNumber !== null && scope.row.passengerNumber !== undefined ? scope.row.passengerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerPercentConv"
                                   align="center"
                                   sortable
                                   :sort-method="sortPercentConvMethods"
                                   label="进店转化率">
                    <template slot-scope="scope">{{ scope.row.customerPercentConv !== null && scope.row.customerPercentConv !== undefined ? scope.row.customerPercentConv : '0.00%' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 进店分析 -->
          <el-tab-pane label="进店分析" name="customerAnalyzeView">
            <div class="customer-analyze-view data-view">
              <div class="panel-title">趋势图</div>
              <div class="panel-charts">
                <v-echart :options="customerAnalyzeEchartOption"></v-echart>
              </div>
              <div class="panel-title">
                <span>详细数据</span>
                <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                  <i class="iconfont">&#xe72d;</i>
                  <div slot="content">
                    新增顾客：选择日期首次来到店内的顾客数
                    <br>
                    <br>
                    店内人数： 选择日期店内的顾客数（排重）
                    <br>
                    <br>
                    进店人次： 选择日期顾客进入店内的次数
                    <br>
                    <br>
                    经过人数： 店外摄像头捕捉到的人数（排重）
                    <br>
                    <br>
                    进店转化率： 进店转化率=店内人数/经过人数*100%
                  </div>
                </el-tooltip>
                <span class="save-csv-link" @click="saveDateToDesktop">
                  <i class="iconfont">&#xe68e;</i>
                  导出CSV</span>
              </div>
              <div class="panel-table">
                <el-table :data="currTableData"
                          border
                          size="small"
                          show-summary
                          :summary-method="tableSummaryMethod"
                          highlight-current-row
                          style="width: 100%">
                  <el-table-column prop="time"
                                   :label="(this.isSameDay? '时间': '日期')"
                                   align="center"
                                   sortable
                                   width="180">
                  </el-table-column>
                  <el-table-column prop="newCustomerNumber"
                                   align="center"
                                   sortable
                                   label="新增顾客">
                    <template slot-scope="scope">{{ scope.row.newCustomerNumber !== null && scope.row.newCustomerNumber !== undefined ? scope.row.newCustomerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerNumber"
                                   align="center"
                                   sortable
                                   label="店内人数">
                    <template slot-scope="scope">{{ scope.row.customerNumber !== null && scope.row.customerNumber !== undefined ? scope.row.customerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerTimes"
                                   align="center"
                                   sortable
                                   label="进店人次">
                    <template slot-scope="scope">{{ scope.row.customerTimes !== null && scope.row.customerTimes !== undefined ? scope.row.customerTimes : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="passengerNumber"
                                   align="center"
                                   sortable
                                   label="经过人数">
                    <template slot-scope="scope">{{ scope.row.passengerNumber !== null && scope.row.passengerNumber !== undefined ? scope.row.passengerNumber : '0' }}</template>
                  </el-table-column>
                  <el-table-column prop="customerPercentConv"
                                   align="center"
                                   sortable
                                   :sort-method="sortPercentConvMethods"
                                   label="进店转化率">
                    <template slot-scope="scope">{{ scope.row.customerPercentConv !== null && scope.row.customerPercentConv !== undefined ? scope.row.customerPercentConv : '0.00%' }}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 区域统计 -->
          <el-tab-pane label="区域统计" name="areaAnalyzeView">
            <div class="area-analyze-view data-view">
              <div class="panel-title">趋势图</div>
              <div class="panel-charts">
                <v-echart :options="areaCustomerFlowEchartOption"></v-echart>
              </div>
              <div class="panel-charts">
                <v-echart :options="customerAreaDataEchartOption"></v-echart>
              </div>
            </div>
          </el-tab-pane>
          <!-- tab - 热力监控 -->
          <el-tab-pane label="热力监控" name="storeMonitoring">
            <div class="data-view">
              <div class="panel-title">
                <span>店面热力图</span>
                <el-tooltip class="instructions" effect="dark" placement="bottom-start">
                  <i class="iconfont">&#xe72d;</i>
                  <div slot="content">
                    通过统计各区域内的人数情况以热力图的形式展现, 并可回顾历史店内人数的热力概况;
                  </div>
                </el-tooltip>
              </div>
              <div class="panel-heatmap">
                <v-mall-map :ad="mallMapData"
                             :scale="mallMapScale"
                             :data="heatMapAreaConfig"
                             :isInit="isInit"
                             type="heatmap">
                </v-mall-map>
                <el-row class="player">
                  <el-col :xs="{ span: 4 }" :sm="{ span: 2 }" class="player-btn">
                    <button class="btn-item" v-show="!heatMapPlayerStatus" @click="heatMapPlay">
                      <i class="iconfont">&#xe61c;</i>
                    </button>
                    <button class="btn-item" v-show="heatMapPlayerStatus" @click="heatMapPlay">
                      <i class="iconfont">&#xe616;</i>
                    </button>
                  </el-col>
                  <el-col :xs="{ span: 19, offset: 1 }" :sm="{ span: 22 }" class="time-bar">
                    <div class="running-bar"
                         ref="domRunningBar"
                         @click="dragHeatMapProgress"
                         :style="{ width: (canRuningPlayBarPercent * 100) + '%' }">
                    </div>
                    <div class="bar-arrow"
                         :style="{ left: (playPointPos * 100) + '%' }">
                    </div>
                    <div class="bar-num"
                         :style="{ left: (playPointPos * 100) + '%' }">
                      {{ currHeatMapPlayTimeStr.hh + ':' + currHeatMapPlayTimeStr.mm }}
                    </div>
                    <div class="bar-timetable">
                      <span v-for="(moment, index) in mallBusinessHoursArr"
                            :key="index"
                            :style="{ left: ((Math.floor((100 / (mallBusinessHoursArr.length - 1)) * 100) / 100) * index) + '%' }"
                            class="timetable-item">
                          {{ moment }}
                      </span>
                    </div>
                  </el-col>
                </el-row>
              </div>
              <!-- ================ -->
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </v-main>
  </div>
</template>
<script type="text/ecmascript-6">
// components
import Main from '@/components/main'
import EChart from '@/components/echarts'
import MallMapComp from '@/components/mallMap'
// element-ui
import { Row, Col, DatePicker, Tooltip, Tabs, TabPane, Table, TableColumn } from 'element-ui'
/**
 * Vue.js(v2.x+) component wrap for countUp.js(v1.x+)
 * @Documents https://github.com/xlsdg/vue-countup-v2
 */
import ICountUp from 'vue-countup-v2'
/**
 * A lightweight canvas library which providing 2d draw for ECharts
 * @Documents https://github.com/ecomfe/zrender
 */
// import Zrender from 'zrender'
/**
 * HTML5 FLV Player
 * @Documents https://github.com/Bilibili/flv.js
 */
// import flvjs from 'flv.js'
import Moment from 'moment'
import { mapGetters } from 'vuex'
// api
import * as APICompass from '@/api/compass.js'
import { APIGetHistoryDataCompare } from '@/api/history.js'
import Config from '@/utils/config.js'

// 单天图表配置============================
import customerNumberEchartInitOption from './customerNumberEchartInitOption.js'
import newCustomerNumberEchartInitOption from './newCustomerNumberEchartInitOption.js'
import customerTimesEchartInitOption from './customerTimesEchartInitOption.js'
import customerAnalyzeEchartInitOption from './customerAnalyzeEchartInitOption.js'
import areaCustomerFlowEchartInitOption from './areaCustomerFlowEchartInitOption.js'
import customerAreaDataEchartInitOption from './customerAreaDataEchartInitOption.js'

// 多天图表配置==================店内人数 进店人次 进店分析
import newCustomerNumberEchartInitOptionOfRange from './newCustomerNumberEchartInitOptionOfRange.js'
import customerNumberEchartInitOptionOfRange from './customerNumberEchartInitOptionOfRange.js'
import customerTimesEchartInitOptionOfRange from './customerTimesEchartInitOptionOfRange.js'
import customerAnalyzeEchartInitOptionOfRange from './customerAnalyzeEchartInitOptionOfRange.js'

const heatMapPlaySpeed = 800

export default {
  name: 'historyData',

  components: {
    // elementUI component
    elRow: Row,
    elCol: Col,
    elDatePicker: DatePicker,
    elTooltip: Tooltip,
    elTabs: Tabs,
    elTabPane: TabPane,
    elTable: Table,
    elTableColumn: TableColumn,
    // countUP component
    ICountUp: ICountUp,
    // 项目自定义组件
    vMain: Main,
    vEchart: EChart,
    vMallMap: MallMapComp
  },

  created () {
    // 更新当前时间
    let startTime = Moment(`${this.mallStartTime}:00:00`, 'hh:mm:ss')
    let endTime = this.mallEndTime === 24 ? Moment(`00:00:01`, 'hh:mm:ss').add(1, 'day') : Moment(`${this.mallEndTime}:00:01`, 'hh:mm:ss')
    this._timerGetCurrTime = setInterval(() => {
      const moment = Moment()
      this.nowTime = moment.format('YYYY-MM-DD HH:mm:ss')
      const seconds = moment.format('s')
      /**
       * 是否在营业时间之内 并且 整点的时候获取数据
       */
      // 每分钟更新次热力图
      if (!parseInt(seconds) && Moment().isBetween(startTime, endTime)) {
        this.APIGetHeatMapData()
      }
    }, 1000)
    // req
    this.getCustomerNumberChartsData()
    this.APIGetHourlyAreaCustomerData()
    this.APIGetAreaFlowData()
    if (Moment().isBetween(startTime, endTime)) {
      this.APIGetHeatMapData().then(() => {
        this.heatMapPlay()
      })
    }
    this.APIGetHistoryDataCompare()
  },

  beforeDestroy () {
    clearInterval(this._timerGetCurrTime)
  },

  data () {
    return {
      // 近 7天 30天 数据比较
      dataComparation: null,
      // 通知信息小喇叭角标红点
      notificationBadge: false,
      // countUp config
      cuConfig: {
        useEasing: true,
        useGrouping: true,
        separator: ',',
        decimal: '.'
      },
      // default tab name
      activeTabsName: 'newCustomerNumberView',
      // 今日客流数据
      todayCustomerData: null,
      // 客流人数相关
      newCustomerNumberEchartOption: null,
      customerNumberEchartOption: null,
      customerTimesEchartOption: null,
      customerAnalyzeEchartOption: null,
      areaCustomerFlowEchartOption: null,
      customerAreaDataEchartOption: null,
      // 当前时间相关 ======================================
      nowTime: Moment().format('YYYY-MM-DD HH:mm:ss'),
      // 用户所选时间
      choosenDate: [Moment().format('YYYY-MM-DD'), Moment().format('YYYY-MM-DD')],
      pickerOptions: {
        disabledDate (time) {
          return time.getTime() > Date.now()
        }
      },
      oneDayChoose: Moment().format('YYYY-MM-DD'),
      activeDateOption: 'first',
      // 区域地图信息 ======================================
      // mallMapData: Config.MALL_MAP_INFO.data,
      // mallMapScale: Config.MALL_MAP_INFO.scale,
      // 热力图状态和数据
      currHeatMapPlayTimestamp: Moment(),
      lastReqHeatMapDataTime: null, // 最后一次请求热区图的时间
      heatMapPlayerStatus: false,
      heatMapAreaConfig: null,
      notTodayHeatMapData: null,
      isInit: false
    }
  },

  computed: {
    // FIXME: store复用
    ...mapGetters([
      'currMallNotifications',
      'mallId',
      'mallStartTime',
      'mallEndTime',
      'mallMapData',
      'mallMapScale',
      'areaCustomerLineData',
      'areaFlowBarData',
      'heatMapData',
      'token'
    ]),
    currTableData () {
      const data = []
      const todayCustomerData = this.todayCustomerData || []
      for (let inx = 0; inx < todayCustomerData.length; inx++) {
        const stats = todayCustomerData[inx]
        let item = {}
        item.newCustomerNumber = stats ? stats.new_customer_num : null
        item.customerNumber = stats ? stats.customer_num : null
        item.passengerNumber = stats ? stats.customer_num_all : null
        item.customerPercentConv = stats ? stats.customer_convert_ratio : null
        item.customerTimes = stats ? stats.customer_times : null
        if (this.isSameDay) {
          item.time = stats.stats_hour < 10 ? `0${stats.stats_hour}:00` : `${stats.stats_hour}:00`
        } else {
          item.time = stats ? stats.stats_date : null
        }
        data.push(item)
      }
      return data
    },
    isSameDay () {
      return this.choosenDate[0] === this.choosenDate[1]
    },
    isTodayByRange () {
      return this.isSameDay && this.choosenDate[0] === Moment().format('YYYY-MM-DD')
    },
    isTodayByTime () {
      return this.oneDayChoose === Moment().format('YYYY-MM-DD')
    },
    // 判断是否切换到区域统计 或者 热力监控
    isOnlyOneDay () {
      return this.activeTabsName === 'storeMonitoring'
    },
    // 当前商场可读取的最后时间
    currMallEndTime () {
      return this.isTodayByRange ? parseInt(Moment().format('HH')) : this.mallEndTime
    },
    mallBusinessHoursArr () {
      let hours = []
      for (let time = this.mallStartTime; time <= this.mallEndTime; time++) {
        let timeStr = time.toString()
        timeStr = timeStr.length === 1 ? `0${timeStr}:00` : `${timeStr}:00`
        hours.push(timeStr)
      }
      return hours
    },
    /**
     * 热力图播放相关的computed ===============================================
     */
    // 判断目前所处时间是否处于后台返回的区间
    isInOpenningHours () {
      const currHour = Moment().format('HH')
      return this.isTodayByTime && currHour >= this.mallStartTime && currHour <= this.mallEndTime
    },
    // 热力图播放的总时长
    currHeatMapTotalTime () {
      return (this.mallEndTime - this.mallStartTime) * 60 * 60 * 1000
    },
    // 热力图可以播放部分所占的百分比
    canRuningPlayBarPercent () {
      if (this.isTodayByTime && Moment().format('HH') >= this.mallStartTime) {
        const tsp = (Moment(this.nowTime).unix() - Moment(this.mallStartTime, 'hh').unix()) * 1000 / this.currHeatMapTotalTime
        return tsp.toFixed(4)
      } else {
        const tsp = 1.0000
        return tsp.toFixed(4)
      }
    },
    // 计算当前播放点的位置
    playPointPos () {
      let a = this.isTodayByTime
        ? (Moment(this.mallStartTime, 'hh').unix() * 1000)
        : Moment(this.oneDayChoose).add(this.mallStartTime, 'hours').unix() * 1000
      let tsp = (this.currHeatMapPlayTimestamp - a) / this.currHeatMapTotalTime > 1
        ? 1
        : (this.currHeatMapPlayTimestamp - a) / this.currHeatMapTotalTime
      return tsp.toFixed(4)
    },
    currHeatMapPlayTimeStr () {
      return {
        hh: this.currHeatMapPlayTimestamp === Moment(this.oneDayChoose).add(this.mallEndTime, 'hours').unix() * 1000 ? this.mallEndTime : Moment(this.currHeatMapPlayTimestamp).hours(),
        mm: Moment(this.currHeatMapPlayTimestamp).format('mm'),
        ss: Moment(this.currHeatMapPlayTimestamp).seconds()
      }
    }
  },
  watch: {
    'choosenDate': function () {
      /**
       * 时间区间选择期, 是不是前后相等, 相当于单日选择期
       */
      if (this.isSameDay) {
        // 前三张表单独一天的情况
        this.getCustomerNumberChartsData()
        this.APIGetAreaFlowData(this.choosenDate[0])
        this.APIGetHourlyAreaCustomerData(this.choosenDate[0])
      } else {
        // 前三张表天数区间的情况
        this.APIDailyRangeStatus(this.choosenDate)
        this.APIGetAreaFlowDataInRange(this.choosenDate).then(this.setAreaCustomerFlowChartOptionOfRangeDays)
        this.APIGetHourlyAreaCustomerDataInRange(this.choosenDate).then(this.setCustomerAreaDataChartsOptionOfRangeDays)
      }
    },
    'oneDayChoose': function () {
      // 通过第二个日期选择器绑定数据 oneDayChoose 发送请求
      // 先清除heatplay里面的定时器 重置状态
      clearInterval(this.heatMapPlayTimer)
      this.heatMapPlayerStatus = false
      this.currHeatMapPlayTimestamp = this.isTodayByTime ? Moment(this.nowTime).unix() * 1000 : Moment(this.oneDayChoose).add(this.mallStartTime, 'hours').unix() * 1000
      this.APIGetHeatMapData().then(() => {
        this.heatMapPlay()
      })
    }
  },

  methods: {
    // 表格中进店转化率排序
    sortPercentConvMethods (a, b) {
      const prev = Number.parseFloat(a.customerPercentConv)
      const curr = Number.parseFloat(b.customerPercentConv)
      if (prev < curr) {
        return -1
      } else if (prev > curr) {
        return 1
      } else {
        return 0
      }
    },
    // 下载表格
    saveDateToDesktop () {
      if (this.isSameDay) {
        window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/hourly-stats/export?api_token=${this.token}&date=${this.choosenDate[0]}`
      } else {
        window.location.href = `${Config.CURR_REQ_URL}/api/shops/${this.mallId}/daily-range-stats/export?api_token=${this.token}&start_date=${this.choosenDate[0]}&end_date=${this.choosenDate[1]}`
      }
    },
    // 表格总计
    tableSummaryMethod ({columns, data}) {
      const sumTxt = '合计'
      let newCustomerNumberTotal = 0
      let customerNumberTotal = 0
      let customerTimesTotal = 0
      let passengerNumberTotal = 0
      for (let inx = 0; inx < data.length; inx++) {
        if (!data) {
          break
        }
        const item = data[inx]
        newCustomerNumberTotal += item.newCustomerNumber
        customerNumberTotal += item.customerNumber
        customerTimesTotal += item.customerTimes
        passengerNumberTotal += item.passengerNumber
      }
      let res = []
      res.push(sumTxt)
      res.push(newCustomerNumberTotal)
      res.push(customerNumberTotal)
      res.push(customerTimesTotal)
      res.push(passengerNumberTotal)
      res.push(passengerNumberTotal ? ((customerNumberTotal / passengerNumberTotal * 10000) / 100).toFixed(2) + '%' : '0.00%')
      return res
    },
    // 获取客户人数图表相关数据
    getCustomerNumberChartsData () {
      this.APIGetHourlyCustomerData(this.choosenDate[0])
        .then((values) => {
          this.todayCustomerData = values.data.stats
          this.setCustomerNumberChartsOption(values)
          this.setNewCustomerNumberChartsOption(values)
          this.setCustomerTimesChartsOption(values)
          this.setCustomerAnalyzeChartsOption(values)
        })
    },
    // 设置新增客户人数的图标option
    setNewCustomerNumberChartsOption (values) {
      let option = Object.assign({}, newCustomerNumberEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: this.mallBusinessHoursArr.slice(0, this.mallBusinessHoursArr.length - 1) })
      option.series.map((item, index) => {
        const stats = values.data.stats || []
        let data = this.isTodayByRange ? new Array(this.currMallEndTime - this.mallStartTime + 1).fill(0) : new Array(this.mallEndTime - this.mallStartTime).fill(0)
        for (let inx = 0; inx < stats.length; inx++) {
          const value = stats[inx]
          data[value.stats_hour - this.mallStartTime] = value.new_customer_num
        }
        item.data = data
        return item
      })
      this.newCustomerNumberEchartOption = option
    },
    // 设置客户人数的图标option
    setCustomerNumberChartsOption (values) {
      let option = Object.assign({}, customerNumberEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: this.mallBusinessHoursArr.slice(0, this.mallBusinessHoursArr.length - 1) })
      option.series.map((item, index) => {
        const stats = values.data.stats || []
        let data = this.isTodayByRange ? new Array(this.currMallEndTime - this.mallStartTime + 1).fill(0) : new Array(this.mallEndTime - this.mallStartTime).fill(0)
        for (let inx = 0; inx < stats.length; inx++) {
          const value = stats[inx]
          data[value.stats_hour - this.mallStartTime] = value.customer_num
        }
        item.data = data
        return item
      })
      this.customerNumberEchartOption = option
    },
    // 设置客户人次的图标option
    setCustomerTimesChartsOption (values) {
      let option = Object.assign({}, customerTimesEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: this.mallBusinessHoursArr.slice(0, this.mallBusinessHoursArr.length - 1) })
      option.series.map((item, index) => {
        const stats = values.data.stats || []
        let data = this.isTodayByRange ? new Array(this.currMallEndTime - this.mallStartTime + 1).fill(0) : new Array(this.mallEndTime - this.mallStartTime).fill(0)
        for (let inx = 0; inx < stats.length; inx++) {
          const value = stats[inx]
          data[value.stats_hour - this.mallStartTime] = value.customer_times
        }
        item.data = data
        return item
      })
      this.customerTimesEchartOption = option
    },
    // 设置进店分析图表option
    setCustomerAnalyzeChartsOption (values) {
      let option = Object.assign({}, customerAnalyzeEchartInitOption)
      option.xAxis = Object.assign({}, option.xAxis, { data: this.mallBusinessHoursArr.slice(0, this.mallBusinessHoursArr.length - 1) })
      option.series.map((item, index) => {
        const stats = values.data.stats || {}
        let data = this.isTodayByRange ? new Array(this.currMallEndTime - this.mallStartTime + 1).fill(0) : new Array(this.mallEndTime - this.mallStartTime).fill(0)
        for (let key in stats) {
          const value = stats[key]
          data[value.stats_hour - this.mallStartTime] = index ? (Number.parseFloat(value.customer_convert_ratio) || 0) : value.customer_num_all
        }
        item.data = data
        return item
      })
      this.customerAnalyzeEchartOption = option
    },
    // 设置区域客流统计
    setAreaCustomerFlowChartOption () {
      const values = this.areaCustomerLineData
      let legendData = []
      let series = []
      for (let inx = 0; inx < this.mallMapData.length; inx++) {
        const mallItem = this.mallMapData[inx]
        const { id } = mallItem
        const data = values ? values[id] : null
        let seriesItemData = this.isTodayByTime ? new Array(this.currMallEndTime - this.mallStartTime + 1).fill(0) : new Array(this.mallEndTime - this.mallStartTime).fill(0)
        if (data) {
          for (let inx = 0; inx < data.length; inx++) {
            const value = data[inx]
            seriesItemData[value.stats_hour - this.mallStartTime] = value.customer_num
          }
        }
        let seriesItem = Object.assign({}, { type: 'line', name: mallItem['name'], data: seriesItemData })
        series.push(seriesItem)
        legendData.push(mallItem['name'])
      }
      let option = Object.assign({}, areaCustomerFlowEchartInitOption)
      option.legend = Object.assign({}, option.legend, { data: legendData })
      option.series = series
      option.xAxis = Object.assign({}, option.xAxis, { data: this.mallBusinessHoursArr.slice(0, this.mallBusinessHoursArr.length - 1) })
      this.areaCustomerFlowEchartOption = option
    },
    // 设置区域总客流与人均时长统计option
    setCustomerAreaDataChartsOption () {
      const areaFlowBarData = this.areaFlowBarData || []
      let xAxisData = []
      let customerTotalData = []
      let customerStayDurationData = []
      for (let inx = 0; inx < this.mallMapData.length; inx++) {
        const mallItem = this.mallMapData[inx]
        const { id } = mallItem
        const item = areaFlowBarData[id]
        xAxisData.push(mallItem['name'])
        customerTotalData.push(item ? item.customer_num : 0)
        customerStayDurationData.push(item ? Math.floor(item.seconds / item.customer_num) : 0)
      }
      let option = Object.assign({}, customerAreaDataEchartInitOption)
      option.xAxis[0] = Object.assign({}, option.xAxis[0], { data: xAxisData })
      option.series[0] = Object.assign({}, option.series[0], { data: customerTotalData })
      option.series[1] = Object.assign({}, option.series[1], { data: customerStayDurationData })
      this.customerAreaDataEchartOption = option
    },
    // 多天图表设置==================================
    // 设置多天新增顾客人数图表的option
    setNewCustomerNumberChartsOptionOfRangeDays (values) {
      let xAxisData = []
      let start = Moment(this.choosenDate[0])
      let end = Moment(this.choosenDate[1])
      let rangeDays = end.diff(start, 'days') + 1
      const todayCustomerData = this.todayCustomerData || []
      let data = []
      for (let i = 0; i < rangeDays; i++) {
        let dateitem = Moment(this.choosenDate[0]).add(i, 'days').format('YYYY-MM-DD')
        xAxisData.push(dateitem)
        let currDateData = todayCustomerData.filter((item) => item.stats_date === dateitem)
        if (currDateData && currDateData.length === 1) {
          data.push(currDateData[0].new_customer_num)
        } else {
          data.push(0)
        }
      }
      let option = Object.assign({}, newCustomerNumberEchartInitOptionOfRange)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisData })
      option.series[0].data = data
      this.newCustomerNumberEchartOption = option
    },
    // 设置多天客户人数图表的option
    setCustomerNumberChartsOptionOfRangeDays (values) {
      let xAxisData = []
      let start = Moment(this.choosenDate[0])
      let end = Moment(this.choosenDate[1])
      let rangeDays = end.diff(start, 'days') + 1
      const todayCustomerData = this.todayCustomerData || []
      let data = []
      for (let i = 0; i < rangeDays; i++) {
        let dateitem = Moment(this.choosenDate[0]).add(i, 'days').format('YYYY-MM-DD')
        xAxisData.push(dateitem)
        let currDateData = todayCustomerData.filter((item) => item.stats_date === dateitem)
        if (currDateData && currDateData.length === 1) {
          data.push(currDateData[0].customer_num)
        } else {
          data.push(0)
        }
      }
      let option = Object.assign({}, customerNumberEchartInitOptionOfRange)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisData })
      option.series[0].data = data
      this.customerNumberEchartOption = option
    },
    // 设置多天客户人次图表的option
    setCustomerTimesChartsOptionOfRangeDays (values) {
      let xAxisData = []
      let start = Moment(this.choosenDate[0])
      let end = Moment(this.choosenDate[1])
      let rangeDays = end.diff(start, 'days') + 1
      const todayCustomerData = this.todayCustomerData || []
      let data = []
      for (let i = 0; i < rangeDays; i++) {
        let dateitem = Moment(this.choosenDate[0]).add(i, 'days').format('YYYY-MM-DD')
        xAxisData.push(dateitem)
        let currDateData = todayCustomerData.filter((item) => item.stats_date === dateitem)
        if (currDateData && currDateData.length === 1) {
          data.push(currDateData[0].customer_times)
        } else {
          data.push(0)
        }
      }
      let option = Object.assign({}, customerTimesEchartInitOptionOfRange)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisData })
      option.series[0].data = data
      this.customerTimesEchartOption = option
    },
    // 设置多天客户进店分析图表的option
    setCustomerAnalyzeChartsOptionOfRangeDays (values) {
      let xAxisData = []
      let start = Moment(this.choosenDate[0])
      let end = Moment(this.choosenDate[1])
      let rangeDays = end.diff(start, 'days') + 1
      const todayCustomerData = this.todayCustomerData || []
      let bardata = []
      let linedata = []
      for (let i = 0; i < rangeDays; i++) {
        let dateitem = Moment(this.choosenDate[0]).add(i, 'days').format('YYYY-MM-DD')
        xAxisData.push(dateitem)
        let currDateData = todayCustomerData.filter((item) => item.stats_date === dateitem)
        if (currDateData && currDateData.length === 1) {
          bardata.push(currDateData[0].customer_num_all)
          linedata.push(Number.parseFloat(currDateData[0].customer_convert_ratio))
        } else {
          bardata.push(0)
          linedata.push(0)
        }
      }
      let option = Object.assign({}, customerAnalyzeEchartInitOptionOfRange)
      option.xAxis = Object.assign({}, option.xAxis, { data: xAxisData })
      option.series.map((item, index) => {
        let data = index ? linedata : bardata
        item.data = data
        return item
      })
      this.customerAnalyzeEchartOption = option
    },
    setAreaCustomerFlowChartOptionOfRangeDays (values) {
      const dateRange = []
      for (let i = 0; i < values.data.dateRange.length; i++) {
        dateRange.unshift(values.data.dateRange[i])
      }
      values = values.data.stats
      const moment = Moment()
      let legendData = []
      let series = []
      const days = Math.abs(Moment(this.choosenDate[0]).diff(Moment(this.choosenDate[1]), 'days'))
      const today = moment.format('YYYY-MM-DD')
      for (let inx = 0; inx < this.mallMapData.length; inx++) {
        const mallItem = this.mallMapData[inx]
        const { id } = mallItem
        const value = values ? values[id] : null
        let stack = []
        if (value) {
          for (const date in value) {
            if (value.hasOwnProperty(date)) {
              const data = value[date] || []
              let item = today === date
                ? new Array(parseInt(moment.format('HH')) - this.mallStartTime).fill(0)
                : new Array(this.mallEndTime - this.mallStartTime + 1).fill(0)
              for (let inx = 0; inx < data.length; inx++) {
                const val = data[inx]
                item[val.stats_hour - this.mallStartTime] = val.customer_num
              }
              stack = [...item, ...stack]
            }
          }
        } else {
          let len = today === this.choosenDate[1]
            ? (parseInt(moment.format('HH')) - this.mallStartTime + 1) + ((days) * (this.mallEndTime - this.mallStartTime + 1))
            : (this.mallEndTime - this.mallStartTime + 1) * (days + 1)
          stack = new Array(len).fill(0)
        }
        // let seriesName = this.mallBusinessHoursArr
        let seriesItem = Object.assign({}, { type: 'line', name: mallItem['name'], data: stack })
        series.push(seriesItem)
        legendData.push(mallItem['name'])
      }
      let option = Object.assign({}, areaCustomerFlowEchartInitOption)
      option.legend = Object.assign({}, option.legend, { data: legendData })
      option.series = series
      // x轴下标
      // dateRange
      let timeStack = []
      for (let i = 0; i < dateRange.length; i++) {
        timeStack[i] = this.mallBusinessHoursArr.map((item) => { return dateRange[i] + ' ' + item })
      }
      timeStack = [].concat(...timeStack)
      timeStack = today === this.choosenDate[1]
        ? timeStack.slice(0, (timeStack.length - (this.mallEndTime - parseInt(moment.format('HH')))))
        : timeStack
      option.xAxis = Object.assign({}, option.xAxis, { data: timeStack })
      option.dataZoom = [
        {
          show: true,
          realtime: true,
          bottom: 24
        },
        {
          type: 'inside',
          realtime: true
        }
      ]
      this.areaCustomerFlowEchartOption = option
    },
    setCustomerAreaDataChartsOptionOfRangeDays (values) {
      values = values.data.stats
      let xAxisData = []
      let customerTotalData = []
      let customerStayDurationData = []
      for (let inx = 0; inx < this.mallMapData.length; inx++) {
        const mallItem = this.mallMapData[inx]
        const { id } = mallItem
        const value = values ? values[id] : null
        xAxisData.push(mallItem['name'])
        let customerTotal = 0
        let customerStayDuration = 0
        if (value) {
          customerTotal = Number(value.customer_sum)
          customerStayDuration = Math.floor(value.avg_seconds)
        }
        customerTotalData.push(customerTotal)
        customerStayDurationData.push(customerStayDuration)
      }
      let option = Object.assign({}, customerAreaDataEchartInitOption)
      option.xAxis[0] = Object.assign({}, option.xAxis[0], { data: xAxisData })
      option.series[0] = Object.assign({}, option.series[0], { data: customerTotalData })
      option.series[1] = Object.assign({}, option.series[1], { data: customerStayDurationData })
      this.customerAreaDataEchartOption = option
    },
    // 用户选择时间
    handleDate: function (n) {
      // FIXME: 修改高亮显示/ switch 语义表示
      let a = Moment().format('YYYY-MM-DD')
      if (!this.isOnlyOneDay) {
        switch (n) {
          case 0:
            this.activeDateOption = 'first'
            this.choosenDate = [a, a]
            break
          case 1:
            this.activeDateOption = 'second'
            let b = Moment().subtract(1, 'day').format('YYYY-MM-DD')
            this.choosenDate = [b, b]
            break
          case 2:
            this.activeDateOption = 'third'
            let c = Moment().subtract(6, 'day').format('YYYY-MM-DD')
            this.choosenDate = [c, a]
            break
          case 3:
            this.activeDateOption = 'fourth'
            let d = Moment().subtract(13, 'day').format('YYYY-MM-DD')
            this.choosenDate = [d, a]
            break
          case 4:
            this.activeDateOption = 'fifth'
            let e = Moment().subtract(29, 'day').format('YYYY-MM-DD')
            this.choosenDate = [e, a]
            break
        }
      } else {
        switch (n) {
          case 0:
            this.activeDateOption = 'first'
            this.oneDayChoose = a
            break
          case 1:
            this.activeDateOption = 'second'
            let b = Moment().subtract(1, 'day').format('YYYY-MM-DD')
            this.oneDayChoose = b
            break
        }
      }
    },

    // 是否初始化canvas
    handleSwitchTab ({ name }) {
      switch (name) {
        case 'storeMonitoring':
          this.$nextTick(() => {
            this.isInit = true
          })
          break
        default:
          this.isInit = false
          break
      }
    },
    // 热力图播放部分代码
    heatMapPlay () {
      this.heatMapPlayerStatus = !this.heatMapPlayerStatus
      if (!this.isTodayByTime && this.currHeatMapPlayTimestamp === Moment(this.oneDayChoose).add(this.mallEndTime, 'hours').unix() * 1000) {
        this.currHeatMapPlayTimestamp = Moment(this.oneDayChoose).add(this.mallStartTime, 'hours').unix() * 1000
      }
      /**
       * [if description] 判断是否播放热力图
       * @param  {[Boolean]} this.heatMapPlayerStatus [description] 播放状态 true: 播放
       */
      if (this.heatMapPlayerStatus) {
        this.getCurrPlayHeatMapData(this.currHeatMapPlayTimestamp)
        this.heatMapPlayTimer = setInterval(() => {
          let timestamp = this.currHeatMapPlayTimestamp
          timestamp += 1000 * 60
          /**
           * [if description]
           * @param  {Number} timestamp [description] 当前播放的时间显示
           * @param  {Number} mallEndTimestamp [description] 当前本地时间显示
           * @return {[type]}           [description] 比较播放时间是否超过本地时间
           */
          if (timestamp > Moment(this.nowTime).unix() * 1000) {
            this.currHeatMapPlayTimestamp = Moment(this.nowTime).unix() * 1000
          } else if (timestamp >= Moment(Moment(this.oneDayChoose).add(this.mallEndTime, 'hours')).unix() * 1000) {
            this.currHeatMapPlayTimestamp = Moment(Moment(this.oneDayChoose).add(this.mallEndTime, 'hours')).unix() * 1000
            this.heatMapPlayerStatus = !this.heatMapPlayerStatus
            clearInterval(this.heatMapPlayTimer)
          } else {
            this.currHeatMapPlayTimestamp = timestamp
          }
          this.getCurrPlayHeatMapData(this.currHeatMapPlayTimestamp)
        }, heatMapPlaySpeed)
      } else {
        clearInterval(this.heatMapPlayTimer)
      }
    },
    getCurrPlayHeatMapData (timestamp) {
      timestamp = Math.floor(timestamp / 1000)
      timestamp = timestamp - (timestamp % 60)
      this.heatMapAreaConfig = this.getHeatMapShapeConfig(timestamp)
    },
    // 当前时间戳的热力情况
    getHeatMapShapeConfig (timestamp) {
      timestamp -= 60
      const data = this.isTodayByTime ? this.heatMapData[timestamp] : this.notTodayHeatMapData[timestamp]
      if (!data || !data.length) {
        return {}
      }
      let maxValArr = 0
      let maxValAeraIdArr = []
      let otherAreaValArr = []
      for (let i = data.length - 1; i >= 0; i--) {
        let currAreaVal = data[i]['customer_num']
        // let currAreaId = data[i]['zone_id']
        if (currAreaVal > maxValArr) {
          maxValArr = currAreaVal
          otherAreaValArr = [...otherAreaValArr, ...maxValAeraIdArr]
          maxValAeraIdArr = [data[i]]
        } else if (currAreaVal === maxValArr) {
          maxValAeraIdArr.push(data[i])
        } else if (currAreaVal !== 0) {
          otherAreaValArr.push(data[i])
        }
      }
      let heatMapAreaConfig = {}
      for (let i = maxValAeraIdArr.length - 1; i >= 0; i--) {
        heatMapAreaConfig[maxValAeraIdArr[i]['zone_id']] = Object.assign({}, maxValAeraIdArr[i], { color: 'rgba(143, 14, 0, .7)' })
      }
      for (let i = otherAreaValArr.length - 1; i >= 0; i--) {
        heatMapAreaConfig[otherAreaValArr[i]['zone_id']] = Object.assign({}, otherAreaValArr[i], { color: 'rgba(143, 119, 0, .5)' })
      }

      return heatMapAreaConfig
    },
    // 拖拽当前播放位置
    dragHeatMapProgress (e) {
      let point = e.offsetX / this.$refs.domRunningBar.offsetWidth
      if (this.isTodayByTime && this.isInOpenningHours) {
        const ts = Math.floor((Moment(this.nowTime).unix() * 1000 - (Moment(this.mallStartTime, 'hh').unix() * 1000)) * point) + (Moment(this.mallStartTime, 'hh').unix() * 1000)
        this.currHeatMapPlayTimestamp = ts
      } else {
        const ats = Math.floor(this.currHeatMapTotalTime * point) + (Moment(this.oneDayChoose).add(this.mallStartTime, 'hours').unix() * 1000)
        this.currHeatMapPlayTimestamp = ats
      }
    },
    // api ======================================================
    /**
     * 将Notification设置为已读
     */
    APISetNotificationsStatus () {
      APICompass.APISetNotificationsStatus({ shop: this.mallId })
        .then(() => {
          this.notificationBadge = false
        })
    },
    /**
     * api: 请求每小时客群数据
     * @param{String}date    日期
     * @param{String}datedecs    当前日期的描述
     */
    APIGetHourlyCustomerData (date) {
      return APICompass.APIGetHourlyCustomerData({ shop: this.mallId, date })
    },
    APIGetCustomerFlowData (date) {
      return APICompass.APIGetCustomerFlowData({ shop: this.mallId, date })
    },
    APIGetHourlyAreaCustomerData (date) {
      APICompass.APIGetHourlyAreaCustomerData({ shop: this.mallId, date })
        .then((res) => {
          this.$store.commit('SET_AREACUSTOMER_DATA', res.data.stats)
          this.setAreaCustomerFlowChartOption()
        })
    },
    APIGetAreaFlowData (date) {
      APICompass.APIGetAreaFlowData({ shop: this.mallId, date })
        .then((res) => {
          this.$store.commit('SET_AREAFLOW_DATA', res.data.stats || null)
          this.setCustomerAreaDataChartsOption()
        })
    },
    APIDailyRangeStatus (dateRange) {
      APICompass.APIDailyRangeStatus({ shop: this.mallId, startDate: dateRange[0], endDate: dateRange[1] })
        .then((res) => {
          this.todayCustomerData = res.data.stats
          this.setNewCustomerNumberChartsOptionOfRangeDays(res.data.stats)
          this.setCustomerNumberChartsOptionOfRangeDays(res.data.stats)
          this.setCustomerTimesChartsOptionOfRangeDays(res.data.stats)
          this.setCustomerAnalyzeChartsOptionOfRangeDays(res.data.stats)
        })
    },
    // 获取热力图数据
    APIGetHeatMapData (start, end) {
      let startT
      let endT
      if (this.isTodayByTime) {
        startT = start ? Moment(start) : this.lastReqHeatMapDataTime || Moment(`${this.mallStartTime}:00:00`, 'hh:mm:ss')
        endT = end ? Moment(end) : Moment(this.nowTime).unix() * 1000
      } else {
        startT = Moment(this.oneDayChoose)
        endT = Moment(this.oneDayChoose).add(this.mallEndTime, 'hour')
      }
      startT = Moment(startT).second(0)
      endT = Moment(endT).second(0)
      return APICompass.APIGetHeatMapData({
        shop: this.mallId,
        start: encodeURIComponent(startT),
        end: encodeURIComponent(endT)
      }).then((res) => {
        if (this.isTodayByTime) {
          this.lastReqHeatMapDataTime = Moment(this.nowTime).unix() * 1000
          this.$store.commit('SET_HEATMAP_DATA', res.data)
        } else {
          this.notTodayHeatMapData = res.data
        }
        return res
      })
    },
    APIGetAreaFlowDataInRange ([start, end]) {
      return APICompass.APIGetAreaFlowDataInRange({ shop: this.mallId, start, end })
    },
    APIGetHourlyAreaCustomerDataInRange ([start, end]) {
      return APICompass.APIGetHourlyAreaCustomerDataInRange({ shop: this.mallId, start, end })
    },
    APIGetHistoryDataCompare () {
      APIGetHistoryDataCompare({ shop: this.mallId })
        .then((res) => {
          this.dataComparation = res.data.stats
        })
    }
  }
}
</script>

<style lang="less" rel="stylesheet/less">
  // scoped
  .history {
    .store-summary {
      width: 100%;
      height: auto;
      box-sizing: border-box;
      background-color: #FFF;
      padding: 10px 20px;
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
      .summary-title {
        padding: 10px 0;
        height: 30px;
        line-height: 30px;
        border-bottom: 1px solid #DFDFDF;
        overflow: hidden;
        .name {
          float: left;
          font-weight: bold;
          font-size: 18px;
        }
        .date {
          float: left;
          margin-left: 30px;
          color: #777;
          font-size: 14px;
        }
      }
      .summary-main {
        margin-top: 10px;
        padding: 10px;
        .summary-wrapper {
          float: left;
          width: 47.5%;
          &:first-child {
            margin-right: 5%;
          }
          .summary-item {
            box-sizing: border-box;
            padding: 20px;
            width: 100%;
            border: 1px solid #DFDFDF;
            .data-compare {
              .compare-item {
                float: left;
                width: 47.5%;
                &:first-child {
                  margin-bottom: 20px;
                }
                &:nth-child(2n+1) {
                  margin-right: 5%
                }
                .label {
                  color: #777;
                  font-size: 14px;
                }
                .value {
                  padding: 5px 0;
                  margin: 10px 0;
                  font-size: 32px;
                  line-height: 32px;
                }
                .desc {
                  font-size: 14px;
                  &.rise {
                    color: #E64340;
                  }
                  &.fall {
                    color: #45C01A;
                  }
                }
                .mom {
                  font-size: 14px;
                }
              }
            }
          }
        }
      }
    }
    .history-tabs {
      box-sizing: border-box;
      margin-top: 20px;
      padding: 10px 20px;
      width: 100;
      background-color: #FFF;
      box-shadow: 0 2px 3px 0 rgba(0, 0, 0, .2);
      .summary-main {
        padding: 10px 0;
        .timeOptions{
          height: 32px;
          line-height: 32px;
          .option{
            margin-right: 20px;
            font-size: 14px;
            color: black;
            cursor: pointer;
            &.active{
              color: rgb(30, 184, 39);
            }
          }
        }
      }
      .data-view {
        .panel-title {
          font-size: 16px;
          .instructions {
            color: #777;
          }
          .save-csv-link {
            float: right;
            cursor: pointer;
            font-size: 13px;
            color: #0269c8;
          }
        }
        .panel-charts {
          padding: 20px 0;
          width: 100%;
          height: 350px;
        }
        .panel-table {
          padding: 20px 0;
          width: 100%;
        }
        .panel-heatmap {
          padding: 20px 0;
          width: 100%;
          height: 550px;
          .player {
            box-sizing: border-box;
            padding: 20px 20px 20px 10px;
            width: 100%;
            height: 70px;
            background-color: #040926;
            user-select: none;
            .player-btn {
              .btn-item {
                position: relative;
                left: 50%;
                transform: translateX(-50%);
                width: 30px;
                height: 30px;
                border-radius: 100%;
                background-color: #FFF;
                outline: none;
              }
            }
            .time-bar {
              position: relative;
              height: 6px;
              transform: translateY(12px);
              background-color: #333;
              color: #888;
              font-size: 12px;
              .running-bar {
                position: absolute;
                top: 0;
                left: 0;
                height: 100%;
                background: linear-gradient(to right,#006eff 0,#004aff 100%);
                &:hover {
                  cursor: pointer;
                }
              }
              .bar-arrow {
                position: absolute;
                top: -15px;
                width: 15px;
                height: 15px;
                transform: translateX(-7px);
                background-image: url('img/compass-down-arrow.svg');
                background-position: center center;
                background-size: contain;
                &:after {
                  content: '';
                  display: block;
                  position: absolute;
                  bottom: -6px;
                  left: 50%;
                  transform: translateX(-50%);
                  width: 0;
                  height: 6px;
                  border-right: 1px solid #040926;
                  overflow: hidden;
                  zoom: 1;
                }
              }
              .bar-num {
                position: absolute;
                top: -28px;
                transform: translateX(-50%);
                text-align: center;
              }
              .bar-timetable {
                position: absolute;
                top: 12px;
                left: 0;
                width: 100%;
                .timetable-item {
                  position: absolute;
                  top: 0;
                  left: 0;
                  transform: translateX(-50%);
                }
              }
            }
          }
        }
      }
    }
  }
</style>
